package com.aiit.ssm.controller;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.aiit.ssm.model.Department;
import com.aiit.ssm.model.Employee;
import com.aiit.ssm.model.ProcResult;
import com.aiit.ssm.service.DepartmentService;
import com.aiit.ssm.service.EmployeeService;
import com.aiit.ssm.utils.ExcelUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@Controller
@RequestMapping("/emp")
public class EmployeeController {
	
	@Autowired
	EmployeeService emptService;
	
	//返回各种客户端都能解析的JSON数据
	@RequestMapping(value="findAllEmployee")
	@ResponseBody
	public ProcResult findAllEmployee(@RequestParam(value="pn",defaultValue="1") int pageNo,Model model) {
		//System.out.println(pageNo);
		//约定：每页查询10条记录，当前查询第pageNo页
		PageHelper.startPage(pageNo, 10);//从第几页开始查询，每次查询10条记录  ：pageNo=(当前页数-1)*10
		List<Employee> empList = emptService.findAllEmployee();
		//System.out.println("总记录数"+empList);
		PageInfo<Employee> pageInfo = new PageInfo<Employee>(empList,5); //5:规定导航栏可以显示页数
		
		System.out.println("总记录数"+pageInfo.getTotal());
		System.out.println("当前页号"+pageInfo.getPageNum()); //页号默认从1开始
		System.out.println("起始索引号"+pageInfo.getStartRow());//索引也是从1开始
		System.out.println("页大小："+pageInfo.getPageSize());
		System.out.println("总页数"+pageInfo.getPages());
		
		return ProcResult.success().bind("pageInfo", pageInfo);
	}
	
	//根据id查询对应员工
	@RequestMapping(value="emp/{id}",method=RequestMethod.GET)
	@ResponseBody
	public ProcResult findEmpById(@PathVariable("id")int id) {
		Employee emp = emptService.findEmployee(id);
		return ProcResult.success().bind("emp", emp);
	}
	
	//保存员工 
	@RequestMapping(value="saveEmpt",method=RequestMethod.POST)
	@ResponseBody
	public ProcResult saveEmp(@Valid Employee emp,BindingResult BindResult) {
		
		if(BindResult.hasErrors()) {
			List<FieldError> fieldErrors = BindResult.getFieldErrors();
			Map<String, String> errors = new HashMap<String, String>();
			for (FieldError fieldError : fieldErrors) {
				String field = fieldError.getField();
				System.out.println(field);
				String defaultMessage = fieldError.getDefaultMessage();
				errors.put(field, defaultMessage);
			}
			return ProcResult.fail().bind("errors", errors);
			
		}else {
			//保存员工数据
			int iRet = emptService.save(emp);
			long totalRecords = emptService.findTotalRecords();//查询最新总记录数
			System.out.println("查询最新总记录数"+totalRecords);
			long totalPages = totalRecords%10==0?totalRecords/10:totalRecords/10+1;
			System.out.println("保存员工数据的totalPages："+totalPages);
			return ProcResult.success().bind("totalPages", totalPages);
		}
	}
	
	//修改员工
	@RequestMapping(value="emp",method=RequestMethod.PUT) //tomcat服务器不接受put请求 通过get请求获取到数据库 emp表里面 id=？ 的用户信息
	@ResponseBody
	public ProcResult updateEmp(@Valid Employee emp,BindingResult BindResult) {
		if(BindResult.hasErrors()) {
			List<FieldError> fieldErrors = BindResult.getFieldErrors();
			Map<String, String> errors = new HashMap<String, String>();
			for (FieldError fieldError : fieldErrors) {
				String field = fieldError.getField();
				System.out.println(field);
				String defaultMessage = fieldError.getDefaultMessage();
				errors.put(field, defaultMessage);
			}
			return ProcResult.fail().bind("errors", errors);
			
		}else {
		System.out.println("修改员工："+emp);
		emptService.updateEmployee(emp);
		return ProcResult.success();
		}
	}
	
	
	//删除员工
	@RequestMapping(value="emp/{id}",method=RequestMethod.DELETE) 
	@ResponseBody
	public ProcResult deleteEmpById(@PathVariable("id")int id) {
		
		System.out.println("删除员工id："+id);
		emptService.deleteEmployee(id);
		return ProcResult.success();
	}
	
	//删除批量员工
	@RequestMapping(value="/deleteMany",method=RequestMethod.POST) 
	@ResponseBody
	public ProcResult deleteEmpById(String id) {
		
		System.out.println("删除员工id："+id);
		System.err.println(id);
       String[] ids=id.split(",");//把数组里的值逗号隔开
        for(int  i=0;i<ids.length;i++) {
        	int idss= Integer.parseInt(ids[i]);
		emptService.deleteEmployee(idss);
		}
		return ProcResult.success();
	}
	
	//模糊搜索
	@RequestMapping("search")
	@ResponseBody
	public ProcResult searchAll(@RequestParam("searchText")String name) {
		System.out.println("searchText："+name);
		name="%"+name+"%";
		List<Employee> list = emptService.searchAll(name);
		//System.out.println("总记录数"+);
		if(list.size()>0) {
			return ProcResult.success().bind("list", list); 
		}else {
			return ProcResult.fail();
		}
		
	}
	
	//自动补全
	@RequestMapping("complement")
	@ResponseBody
	public ProcResult searchEmpByName() {
		System.out.println("searchEmpByName：");
		
		ArrayList<String> empNameList =emptService.searchName();
		//System.out.println("empNameList："+empNameList);
		return ProcResult.success().bind("empNameList", empNameList);
	}
	
	
	@RequestMapping("countTotal")
	@ResponseBody
	public ProcResult countTotal(@RequestParam("name")String name) {
		
		int iRet = emptService.findEmpByName(name);
		return ProcResult.success().bind("iRet", iRet);
		
	}
	
	
	@ResponseBody
	@RequestMapping(value = "/excel/InputExcel.do")
	public String InputExcel(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws Exception {
		System.out.println("上传");
		String flag = "02";// 上传标志
		if (!file.isEmpty()) {
			try {
				String originalFilename = file.getOriginalFilename();// 原文件名字
				//log.info("文件名：" + originalFilename);
				InputStream is = file.getInputStream();// 获取输入流
				flag = emptService.InputExcel(is, originalFilename);
			} catch (Exception e) {
				flag = "03";// 上传出错
				e.printStackTrace();
			}
		}
		return flag;
	}

	
	
	@RequestMapping(value = "/excel/OutputExcel.do", produces = "application/form-data; charset=utf-8")
	@ResponseBody
	public String OutputExcel(HttpServletRequest request, HttpServletResponse response) throws Exception {
		System.out.println("导出");
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html,charset=utf-8");
 
		List<Employee> list = emptService.OutputExcel();
 
		String message =ExcelUtil.OutExcel(request, response, list);
		if (message.equals("fail")) {
			ServletOutputStream out = response.getOutputStream();
			message = "导出失败，请重试";
			String s = "<!DOCTYPE HTML><html><head><script>alert('" + message + "');</script></head><body></body></html>";
			out.print(s);
		}
		return null;
	}

}
